<?php
/**
 * Autor:   Miguel A. Zilli
 * Email:   miguelzilli@gmail.com
 */

class Seguro extends AppModel {
    var $name = 'Seguro';
    var $useTable = 'seguros';
    var $primaryKey = 'id';
    var $displayField = 'tipo_seg';
    var $recursive = 0;
    var $order=array(
        'Seguro.tipo_seg'=>'ASC'
    );

    var $validate = array(
        //PRODUCE ERROR Y NO SE POR QUE?
        //'tipo_seg'=>array(
        //   array('rule'=>'notEmpty','message'=>'Debe completar este dato.','required'=>true)
        //),
         'monto_seg'=>array(
            array('rule'=>'numeric','message'=>'Solo se permiten números.','allowEmpty'=>true)
        )
    );

    var $belongsTo = array(
        'Revision' => array(
            'className' => 'Revision',
            'foreignKey' => 'revision_id'
        )
    );

    public function beforeSave($options = array()){
        $this->data['Seguro']['fch_seg'] = $this->formatDate($this->data['Seguro']['fch_seg']);
        //if(empty($this->data['Seguro']['fch_seg'])){
        //    $this->data['Seguro']['fch_seg'] = date('Y-m-d H:i');
        //}
        if(!empty($this->data['Seguro'])){
            foreach($this->data['Seguro'] as $campo=>$valor){
                if ($campo!='fch_seg'){
                    $this->data['Seguro'][$campo]=strtoupper($valor);
                }
            }
        }
        return parent::beforeSave($options);
    }

    public function afterFind($result) {
        foreach ($result as $clave => $valor) {
            if (isset($valor['Seguro']['fch_seg'])) {
                $result[$clave]['Seguro']['fch_seg'] = $this->formatoFechatAfterFind($valor['Seguro']['fch_seg']);
            }
        }
        return parent::afterFind($result);
    }

    function formatoFechatAfterFind($fecha) {
        return date('d-m-Y', strtotime($fecha));
    }

    function formatDate($dateToFormat){
        $pattern1 = '/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/i';
        $pattern2 = '/^([0-9]{4})\/([0-9]{2})\/([0-9]{2})$/i';
        $pattern3 = '/^([0-9]{2})-([0-9]{2})-([0-9]{4})$/i';
        $pattern4 = '/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/i';

        $coincidences = array();

        if(preg_match($pattern1, $dateToFormat)){
            $newDate = $dateToFormat;
        }elseif(preg_match($pattern2, $dateToFormat, $coincidences)){
            $newDate = $coincidences[1] . '-' . $coincidences[2] . '-' . $coincidences[3];
        }elseif(preg_match($pattern3, $dateToFormat, $coincidences)){
            $newDate = $coincidences[3] . '-' . $coincidences[2] . '-' . $coincidences[1];
        }elseif(preg_match($pattern4, $dateToFormat, $coincidences)){
            $newDate = $coincidences[3] . '-' . $coincidences[2] . '-' . $coincidences[1];
        }else{
            $newDate = null;
        }
        return $newDate;
    }
}
?>